package com.tongzhan.service.impl;

import com.tongzhan.base.PageInfo;
import com.tongzhan.base.Return;
import com.tongzhan.data.vo.PersonnelDetailsVO;
import com.tongzhan.data.vo.PersonnelVO;
import com.tongzhan.data.vo.PicVO;
import com.tongzhan.data.vo.SiteVO;
import com.tongzhan.entity.User;
import com.tongzhan.entity.religion.Personnel;
import com.tongzhan.entity.religion.Site;
import com.tongzhan.repository.UserRepository;
import com.tongzhan.repository.religion.PersonnelRepository;
import com.tongzhan.repository.religion.SiteRepository;
import com.tongzhan.service.PersonnelService;
import com.tongzhan.utils.SnowFlakeUtils;
import com.tongzhan.utils.ThreadLocalUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
@Service
public class PersonnelServiceImpl implements PersonnelService {

    @Autowired
    private UserRepository userRepository;

    @Autowired
    private SiteRepository siteRepository;

    @Autowired
    private PersonnelRepository personnelRepository;

    @Override
    public Return newPersonnel(String userId, Personnel personnel) {
        String personnelCode = personnel.getPersonnelCode();
        if (StringUtils.isEmpty(personnelCode)) {
            //为新增
            //用户信息
            User user = userRepository.findByPrimaryKey(userId);
            if (user != null) {
                personnel.setStreetCode(user.getStreetCode());
                personnel.setStreetName(user.getStreetName());
                personnel.setReligionCode(user.getReligionCode());
                personnel.setReligionName(user.getReligionName());
                personnel.setSiteCode(user.getSiteCode());
                personnel.setSiteName(user.getSiteName());
            }
            //生成人员信息编码
            SnowFlakeUtils snow = new SnowFlakeUtils(4, 4);
            personnel.setPersonnelCode(String.valueOf(snow.nextId()));
            personnel.setCreateTime(LocalDateTime.now());
            personnelRepository.insert(personnel);
        } else {
            //为修改
            Personnel updatePersonnel = personnelRepository.findByPrimaryKey(personnelCode);
            if (updatePersonnel != null) {
                personnel.setStreetCode(updatePersonnel.getStreetCode());
                personnel.setStreetName(updatePersonnel.getStreetName());
                personnel.setReligionCode(updatePersonnel.getReligionCode());
                personnel.setReligionName(updatePersonnel.getReligionName());
                personnel.setSiteCode(updatePersonnel.getSiteCode());
                personnel.setSiteName(updatePersonnel.getSiteName());
                personnel.setOutTime(updatePersonnel.getOutTime());
                personnel.setCreateTime(personnel.getCreateTime());
            }
            personnel.setUpdateTime(LocalDateTime.now());
            personnelRepository.updateByPrimaryKey(personnel);
        }
        return new Return(Return.SUCCESS, "操作成功");
    }

    @Override
    public Return getPersonList(String userId, String siteCode, Integer type, Integer page, Integer size, String religionCode) {
        //用户信息
        User user = userRepository.findByPrimaryKey(userId);
        if (user == null) {
            return new Return(Return.FAIL, "用户不存在");
        }
        //权限编码
        String code = user.getDutiesCode();
        //查询条件
        Query query = new Query();
        query.with(Sort.by(Sort.Direction.ASC, "ReligionCode", "SiteCode"));
        if (!"03".equals(code) && StringUtils.isNotEmpty(religionCode)) {
            query.addCriteria(Criteria.where("ReligionCode").is(religionCode));
        }
        if ("02".equals(code) || ThreadLocalUtil.STREET_CODE.equals(code)) {
            //街道
            query.addCriteria(Criteria.where("StreetCode").is(user.getStreetCode()));
        } else if ("03".equals(code)) {
            //团体
            query.addCriteria(Criteria.where("ReligionCode").is(user.getReligionCode()));
        } else if ("05".equals(code) || ThreadLocalUtil.VILLAGE_CODE.equals(code)) {
            //村社区
            query.addCriteria(Criteria.where("VillageCode").is(user.getVillageCode()));
        } else if ("04".equals(code) || "07".equals(code)) {
            //场所、民间信仰点
            query.addCriteria(Criteria.where("SiteCode").is(user.getSiteCode()));
        }
        //防止筛选条件重复
        if (!"04".equals(code) && !"07".equals(code) && StringUtils.isNotEmpty(siteCode)) {
            query.addCriteria(Criteria.where("SiteCode").is(siteCode));
        }
        //排除暂住已离开人员
        query.addCriteria(Criteria.where("OutTime").is(null));
        //场所VO
        List<SiteVO> siteVOS = new ArrayList<>();
        //场所列表
        List<Site> siteList = siteRepository.findAll(query);
        if (!CollectionUtils.isEmpty(siteList)) {
            for (Site site : siteList) {
                SiteVO siteVO = new SiteVO();
                siteVO.setSiteCode(site.getSiteCode());
                siteVO.setSiteName(site.getSiteName());
                siteVOS.add(siteVO);
            }
        }
        //封装返回数据
        Map<String, Object> map = new HashMap<>();
        map.put("siteList", siteVOS);
        if (type != null) {
            query.addCriteria(Criteria.where("Type").is(type));
        }
        Page<Personnel> personnels = personnelRepository.findPage(query, PageRequest.of(page - 1, size));
        //人员信息列表
        List<Personnel> personnelList = personnels.getContent();
        //分页信息
        PageInfo pageInfo = new PageInfo();
        pageInfo.setPage(page);
        pageInfo.setSize(personnelList.size());
        pageInfo.setTotal(personnels.getTotalElements());
        map.put("pageInfo", pageInfo);
        //人员VO
        List<PersonnelVO> vos = new ArrayList<>();
        for (Personnel personnel : personnelList) {
            PersonnelVO vo = new PersonnelVO();
            vo.setPersonnelCode(personnel.getPersonnelCode());
            vo.setName(personnel.getRealName());
            vo.setSiteName(personnel.getSiteName());
            vo.setCause(personnel.getCause());
            //人员类型
            if (personnel.getType() == 0) {
                if (personnel.getOutTime() == null) {
                    vo.setIsLeave("暂住：未离开");
                } else {
                    vo.setIsLeave("暂住：已离开");
                }
            } else {
                vo.setIsLeave("常住");
            }
            List<PicVO> picList = new ArrayList<>();
            //正面照
            String frontPhoto = personnel.getFrontPhoto();
            if (StringUtils.isNotEmpty(frontPhoto)) {
                PicVO picVO = new PicVO();
                picVO.setPath(frontPhoto);
                picList.add(picVO);
            }
            //身份证正反面
            String certificates = personnel.getCertificates();
            if (StringUtils.isNotEmpty(certificates)) {
                String[] files = certificates.split(",");
                for (String file : files) {
                    PicVO picVO = new PicVO();
                    picVO.setPath(file);
                    picList.add(picVO);
                }
            }
            vo.setPicList(picList);
            vos.add(vo);
        }
        map.put("personList", vos);
        return new Return(map);
    }

    @Override
    public Return personDetails(String personnelCode) {
        //人员信息
        Personnel personnel = personnelRepository.findByPrimaryKey(personnelCode);
        //VO
        PersonnelDetailsVO vo = new PersonnelDetailsVO();
        if (personnel != null) {
            BeanUtils.copyProperties(personnel, vo);
            vo.setName(personnel.getRealName());
            BeanUtils.copyProperties(personnel, vo);
            List<PicVO> picList = new ArrayList<>();
            //正面照
            String frontPhoto = personnel.getFrontPhoto();
            if (StringUtils.isNotEmpty(frontPhoto)) {
                PicVO picVO = new PicVO();
                picVO.setPath(frontPhoto);
                picList.add(picVO);
            }
            //身份证正反面
            String certificates = personnel.getCertificates();
            if (StringUtils.isNotEmpty(certificates)) {
                String[] files = certificates.split(",");
                for (String file : files) {
                    PicVO picVO = new PicVO();
                    picVO.setPath(file);
                    picList.add(picVO);
                }
            }
            //居住证
            if (StringUtils.isNotEmpty(personnel.getResidences())) {
                String[] files = certificates.split(",");
                for (String file : files) {
                    PicVO picVO = new PicVO();
                    picVO.setPath(file);
                    picList.add(picVO);
                }
            }
            //教师证
            String teachingStaff = personnel.getTeachingStaff();
            if (StringUtils.isNotEmpty(teachingStaff)) {
                PicVO picVO = new PicVO();
                picVO.setPath(teachingStaff);
                picList.add(picVO);
            }
            vo.setPicList(picList);
        }
        return new Return(vo);
    }

    @Override
    public Return leave(String personnelCode) {
        Personnel personnel = personnelRepository.findByPrimaryKey(personnelCode);
        if (personnel == null) {
            return new Return(Return.FAIL, "人员信息不存在");
        }
        personnel.setOutTime(LocalDate.now());
        personnel.setUpdateTime(LocalDateTime.now());
        personnelRepository.updateByPrimaryKey(personnel);
        return new Return(Return.SUCCESS, "操作成功");
    }

    @Override
    public Return returnPersonDetails(String personnelCode) {
        //人员信息
        Personnel personnel = personnelRepository.findByPrimaryKey(personnelCode);
        return new Return(personnel);
    }

    @Override
    public Return delete(String personnelCode) {
        personnelRepository.deletePrimaryKey(personnelCode);
        return new Return(Return.SUCCESS, "删除成功");
    }
}
